package org.example.aienglishapp.controller.article;

import org.example.aienglishapp.dto.article.TranslationConverter;
import org.example.aienglishapp.dto.article.TranslationDTO;
import org.example.aienglishapp.entity.article.Translation;
import org.example.aienglishapp.service.article.TranslationService;
import org.example.aienglishapp.config.others.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/translations")
public class TranslationController {

    @Autowired
    private TranslationService translationService;

    @Autowired
    private RedisService redisService;

    private static final String TRANSLATION_CACHE_PREFIX = "translation:article:";

    @PostMapping
    public ResponseEntity<Void> addTranslation(@RequestBody TranslationDTO translationDTO) {
        // 转换 DTO 到实体
        Translation translation = TranslationConverter.toEntity(translationDTO);

        // 添加翻译记录
        translationService.addTranslation(translation);

        // 同步翻译结果到 Redis
        redisService.set(TRANSLATION_CACHE_PREFIX + translation.getArticleId(), translation);

        return ResponseEntity.ok().build();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Void> updateTranslation(@PathVariable Long id, @RequestBody TranslationDTO translationDTO) {
        // 确保 ID 一致
        translationDTO.setId(id);

        // 转换 DTO 到实体
        Translation translation = TranslationConverter.toEntity(translationDTO);

        // 更新翻译记录
        translationService.updateTranslation(translation);

        // 同步更新到 Redis
        redisService.set(TRANSLATION_CACHE_PREFIX + translation.getArticleId(), translation);

        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTranslation(@PathVariable Long id) {
        // 删除指定ID的翻译记录
        translationService.deleteTranslation(id);

        // 从 Redis 删除缓存
        redisService.delete(TRANSLATION_CACHE_PREFIX + id);

        return ResponseEntity.ok().build();
    }

    @GetMapping("/get/{id}")
    public ResponseEntity<TranslationDTO> getTranslationById(@PathVariable Long id) {
        // 先从Redis缓存获取翻译
        Translation translation = (Translation) redisService.get(TRANSLATION_CACHE_PREFIX + id);
        if (translation == null) {
            // 如果Redis中没有，从数据库获取
            translation = translationService.getTranslationById(id);
            if (translation != null) {
                // 将从数据库中获取的翻译内容缓存到Redis
                redisService.set(TRANSLATION_CACHE_PREFIX + id, translation);
            }
        }

        if (translation == null) {
            return ResponseEntity.notFound().build();
        }

        // 转换为DTO并返回
        TranslationDTO translationDTO = TranslationConverter.toDTO(translation);
        return ResponseEntity.ok(translationDTO);
    }

    // 根据文章ID获取翻译内容
    @GetMapping("/getbyarticle/{articleId}")
    public ResponseEntity<TranslationDTO> getTranslationByArticleId(@PathVariable Long articleId) {
        // 先从Redis缓存获取翻译
        Translation translation = (Translation) redisService.get(TRANSLATION_CACHE_PREFIX + articleId);
        if (translation == null) {
            // 如果Redis中没有，从数据库获取
            translation = translationService.getTranslationByArticleId(articleId);
            if (translation != null) {
                // 将从数据库中获取的翻译内容缓存到Redis
                redisService.set(TRANSLATION_CACHE_PREFIX + articleId, translation);
            }
        }

        if (translation == null) {
            return ResponseEntity.notFound().build();
        }

        // 转换为DTO并返回
        TranslationDTO translationDTO = TranslationConverter.toDTO(translation);
        return ResponseEntity.ok(translationDTO);
    }

    @GetMapping
    public ResponseEntity<List<TranslationDTO>> getAllTranslations() {
        // 获取所有翻译记录
        List<Translation> translations = translationService.getAllTranslations();
        List<TranslationDTO> translationDTOs = translations.stream()
                .map(TranslationConverter::toDTO)
                .collect(Collectors.toList());
        return ResponseEntity.ok(translationDTOs);
    }

    @PostMapping("/translateAndSave")
    public ResponseEntity<TranslationDTO> translateAndSave(
            @RequestParam Long articleId) {

        try {
            // 调用 TranslationService 的 translateAndSave 方法来翻译并保存翻译记录
            Translation translation = translationService.translateAndSave(articleId);

            // 同时将翻译结果缓存到 Redis
            redisService.set(TRANSLATION_CACHE_PREFIX + articleId, translation);

            // 将翻译记录转换为 DTO 并返回
            TranslationDTO translationDTO = TranslationConverter.toDTO(translation);
            return ResponseEntity.ok(translationDTO);  // 返回 200 OK 和翻译结果
        } catch (Exception e) {
            // 如果发生错误，返回 500 错误和错误信息
            return ResponseEntity.status(500).body(null);
        }
    }
}